{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Add Header"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from numpy.random import randn\n",
    "from datetime import datetime\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Matplotlib Global Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.rc('figure', figsize=(15,10))\n",
    "font_option = {\n",
    "    'family': 'monospace',\n",
    "    'weight': 'bold',\n",
    "    'size': '12'\n",
    "}\n",
    "plt.rc('font', **font_option)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot figure: using add_subplot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure()\n",
    "ax1 = fig.add_subplot(2,2,1)\n",
    "ax2 = fig.add_subplot(2,2,2)\n",
    "ax3 = fig.add_subplot(2,2,3)\n",
    "plt.plot(randn(50).cumsum(), 'k--')\n",
    "\n",
    "ax1.hist(randn(500), bins=20, color='k', alpha=0.3)\n",
    "ax2.scatter(x=np.arange(30), y=np.arange(30) + 3 * randn(30))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot figure: using subplots"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(2, 2)\n",
    "\n",
    "axes[1,0].plot(randn(50).cumsum(), 'k--')\n",
    "\n",
    "axes[0,0].hist(randn(500), bins=20, color='k', alpha=0.3)\n",
    "axes[0,1].scatter(x=np.arange(30), y=np.arange(30) + 3 * randn(30))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Adjusting the spacing around the subplots"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)\n",
    "for i in range(2):\n",
    "    for j in range(2):\n",
    "        axes[i,j].hist(x=randn(500), bins=50, color='k', alpha=0.5)\n",
    "plt.subplots_adjust(wspace=0, hspace=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Colors, Markers and Line Sytles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = randn(10).cumsum()\n",
    "fig, axes = plt.subplots(nrows=2, ncols=2)\n",
    "axes[0,0].plot(data, linestyle='--')\n",
    "axes[0,1].plot(data, 'ko--')\n",
    "axes[1,0].plot(data, color='k', marker='o', linestyle='--')\n",
    "axes[1,1].plot(data, color='b', linestyle='dashed')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Titles, Ticks, Lables and Legend"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15,10))\n",
    "ax1 = fig.add_subplot(1,1,1)\n",
    "ax1.plot(randn(1000).cumsum(), 'k', label='one')\n",
    "ax1.plot(randn(1000).cumsum(), 'b--', label='two')\n",
    "ax1.plot(randn(1000).cumsum(), 'r.', label='tree')\n",
    "ax1.set_title(\"I'm title\")\n",
    "ax1.set_xticks([200, 400, 600, 800, 1000])\n",
    "ax1.set_xticklabels(['l2', 'l4', 'l6', 'l8', 'l10'], rotation=30, fontsize='medium')\n",
    "ax1.legend(loc='best')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Annotations and Drawing on the plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "ax = fig.add_subplot(1,1,1)\n",
    "ax.set_title('Annotation Test')\n",
    "# 指定0列为行索引\n",
    "data = pd.read_csv('./pydata-book/examples/spx.csv', index_col=0, parse_dates=True)\n",
    "\n",
    "# data = pd.read_csv('./pydata-book/examples/spx.csv', parse_dates=True)\n",
    "print(data[:5])\n",
    "spx = data['SPX'] # Series\n",
    "print(spx[:5])\n",
    "spx.plot(ax=ax, style='k--')\n",
    "\n",
    "# limit 2007 - 20110\n",
    "ax.set_xlim(['1/1/2007', '1/1/2010'])\n",
    "ax.set_ylim([600, 1800])\n",
    "\n",
    "crisis_data = [\n",
    "    (datetime(2007, 10,11), 'AA'),\n",
    "    (datetime(2008, 3,12), 'BB'),\n",
    "    (datetime(2008, 9,15), 'CC')]\n",
    "\n",
    "for date, label in crisis_data:\n",
    "    # print(spx.asof(date))\n",
    "    ax.annotate(label, xy=(date, spx.asof(date)+50),\n",
    "                xytext=(date, spx.asof(date)+200),\n",
    "                arrowprops=dict(facecolor='black'),\n",
    "                horizontalalignment='left', verticalalignment='top'\n",
    "               )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plotting function in pandas\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = np.random.randn(10).cumsum()\n",
    "print(data)\n",
    "s1 = pd.Series(data=data, index=np.arange(0, 100, 10))\n",
    "s1.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = np.random.randn(10, 4).cumsum(0)\n",
    "print(data)\n",
    "df1 = pd.DataFrame(data=data, columns=('A','B','C','D'), index=np.arange(0, 100, 10))\n",
    "df1.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(2, 1)\n",
    "s2 = pd.Series(\n",
    "    data=np.random.randn(16).cumsum(),\n",
    "    index=list('abcdefghijklmnop')\n",
    ")\n",
    "s2.plot(kind='bar', ax=axes[0], color='k', alpha=0.7)\n",
    "s2.plot(kind='barh', ax=axes[1], color='k', alpha=0.7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df2 = pd.DataFrame(\n",
    "    data=np.random.rand(6,4),\n",
    "    index=['one','two', 'tree', 'four', 'five', 'six'],\n",
    "    columns=pd.Index(data=list('ABCD'), name='Genus')\n",
    ")\n",
    "print(df2)\n",
    "df2.plot(kind='bar')\n",
    "df2.plot(kind='barh', stacked=True, alpha=0.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "tips = pd.read_csv('./pydata-book/examples/tips.csv')\n",
    "# print(type(tips.size))\n",
    "# tips.size is the tips's size, is not column 'size', so using tips['size'] instead.\n",
    "day_counts = pd.crosstab(tips.day, tips['size'])\n",
    "day_counts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tips['pct'] = tips['tip'] / tips['total_bill']\n",
    "tips['pct'].hist(bins=50)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
